<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>姓名案例-watch实现</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    
    <div id="root">
        姓: <input type="text" v-model="firstName"> <br>
        名: <input type="text" v-model="lastName"> <br>
        <span>全名: {{fullName}}</span>
    </div>

    <script>

        const vm = new Vue({
            el: '#root',
            data: {
               firstName: '李',
               lastName: '葵',
               fullName: ''
            },
            watch: {
                /* 
                    1.watch中的firstName会被调用,当data中的firstName被改变时
                    2.watch中的fistName的this是vm
                */
                //监测姓--精简写法
                // firstName(newValue, oldValue){ 
                //     // console.log('firstName被别人改了', newValue, oldValue);
                //     this.fullName = newValue + '-' + this.lastName;
                // },
                //监测姓--完整写法
                firstName: {
                    immediate: true,//如果为true,那么handler在初始化时就会调用一次.
                    handler(newValue, oldValue){
                        this.fullName = newValue + '-' + this.lastName 
                    }
                },
                lastName(newValue, oldValue){ 
                    // console.log('firstName被别人改了', newValue, oldValue);
                    this.fullName = this.firstName + '-' + newValue;
                }
            }
        })

        //watch的第二种写法,类似el的第二种写法
        // vm.$watch('firstName', {
        //     immediate: true,
        //     handler(newValue, oldValue){
        //         //这里不是属于直接vue管理的,可以用箭头函数
                // setTimeout(()=>{
                //       this.fullName = newValue + '-' + this.lastName  
                // }, 1000)
        //     }
        // })
    </script>
</body>
</html>